﻿namespace Pibby.Core.IO
{
	using System;

	public static class FileSizeInterpreter
	{
		/// <summary>
		/// Convert bytes to a human readable format
		/// </summary>
		/// <param name="fileSize">the number bytes</param>
		/// <returns>apropriate amount of bytes (Gb, Mb, Kb, bytes)</returns>
		public static string InterpretSize(long fileSize)
		{
			string formatted = string.Empty;

			const double ThousandAndTwentyFour = 1024;

			if (fileSize < ThousandAndTwentyFour)
			{
				formatted = string.Format(System.Globalization.CultureInfo.CurrentUICulture, "{0} bytes", fileSize);
			}
			else
			{
				double value = fileSize;
				value = value / ThousandAndTwentyFour;
				string unit = "KB";

				if (value >= 1000)
				{
					value = Math.Floor(value);
					value = value / ThousandAndTwentyFour;
					unit = "MB";
				}

				if (value >= 1000)
				{
					value = Math.Floor(value);
					value = value / ThousandAndTwentyFour;
					unit = "GB";
				}

				if (value >= 1000)
				{
					value = Math.Floor(value);
					value = value / ThousandAndTwentyFour;
					unit = "TB";
				}

				if (value < 10)
				{
					value = Math.Floor(value * 100) / 100;
					formatted = string.Format(System.Globalization.CultureInfo.CurrentUICulture, "{0:n2} {1}", value, unit);
				}
				else if (value < 100)
				{
					value = Math.Floor(value * 10) / 10;
					formatted = string.Format(System.Globalization.CultureInfo.CurrentUICulture, "{0:n1} {1}", value, unit);
				}
				else
				{
					value = Math.Floor(value * 1) / 1;
					formatted = string.Format(System.Globalization.CultureInfo.CurrentUICulture, "{0:n0} {1}", value, unit);
				}
			}

			return formatted;
		}
	}
}
